<template>
  <div class="app-container">
    <!-- 顶部导航栏 -->
    <el-header class="navbar">
      <div class="container">
        <router-link to="/" class="logo">内容平台</router-link>

        <el-menu
          mode="horizontal"
          :default-active="activeMenu"
          router
          class="main-nav"
        >
          <el-menu-item index="/">首页</el-menu-item>
          <el-menu-item index="/categories">分类</el-menu-item>
          <el-menu-item index="/hot">热门</el-menu-item>
          <el-menu-item index="/about">关于</el-menu-item>
        </el-menu>

        <div class="user-actions">
          <el-input
              v-model="searchQuery"
              placeholder="搜索内容..."
              class="search-input"
              clearable
          >
            <template #append>
              <el-button icon="el-icon-search" @click="handleSearch"  /><span style="font-weight: bold;">搜索</span>
            </template>
          </el-input>

          <!-- 登录/用户信息区域 -->
          <div class="auth-buttons" v-if="!authStore.isAuthenticated">
            <el-button type="text" @click="loginDialogVisible = true">登录</el-button>
            <el-button type="primary" @click="registerDialogVisible = true">注册</el-button>
          </div>

          <div class="user-info" v-else>

            <el-dropdown >
              <div class="dropdown-trigger">
                <span class="user-name">{{ authStore.user.nickname }}</span>
                <el-avatar
                    :size="36"
                    :src="authStore.user.avatar"
                    style="vertical-align: middle; margin-left: 8px;"
                >
                <img src="https://默认头像.png"/>
                </el-avatar>
              </div>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item  @click="$router.push('/newProfile')">个人中心</el-dropdown-item>
                  <el-dropdown-item  @click="$router.push('/addContent')">发布新闻</el-dropdown-item>
                  <el-dropdown-item @click="handleLogout">退出登录</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
      </div>
    </el-header>

    <!-- 登录对话框 -->
    <el-dialog
  v-model="loginDialogVisible"
  title="登录后内容更精彩"
  width="380px"
  :before-close="handleDialogClose"
  class="custom-login-dialog"
>
  <div class="login-content">
    <el-tabs v-model="activeLoginMethod" stretch>
      <el-tab-pane label="手机登录" name="phone">
        <el-form
          :model="phoneLoginForm"
          :rules="phoneLoginRules"
          ref="phoneLoginFormRef"
          label-position="top"
        >
          <el-form-item prop="phone">
            <div class="phone-input">
              <el-input
                v-model="phoneLoginForm.phone"
                placeholder="请输入手机号"
                class="phone-number-input"
              />
            </div>
          </el-form-item>

          <el-form-item prop="password">
            <div class="code-input">
              <el-input
                v-model="phoneLoginForm.password"
                placeholder="请输入密码"
              />
            </div>
          </el-form-item>
        </el-form>
      </el-tab-pane>

      <el-tab-pane label="扫码登录" name="qrcode">
        <div class="qrcode-login">
          <div class="qrcode-placeholder">
            <el-icon :size="60" color="#999"><Picture /></el-icon>
            <p></p>
            <p>在"我的"界面左上角点击扫一扫登录</p>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>

    <div class="login-agreement">
      <el-checkbox v-model="agreeAgreement">
        登录即同意《用户协议》和《隐私政策》
      </el-checkbox>
    </div>

    <el-button
      type="primary"
      @click="handlePhoneLogin"
      :loading="loginLoading"
      :disabled="!agreeAgreement"
      class="login-btn"
    >
      登录
    </el-button>

    <div class="other-login-methods">
      <div class="divider">
        <span class="divider-text">其他登录</span>
      </div>
      <div class="social-logins">
        <el-tooltip content="微信登录" placement="top">
          <el-icon :size="24"><ChatDotRound /></el-icon>
        </el-tooltip>
        <el-tooltip content="QQ登录" placement="top">
          <el-icon :size="24"><ChatLineRound /></el-icon>
        </el-tooltip>
        <el-tooltip content="微博登录" placement="top">
          <el-icon :size="24"><ChatLineSquare /></el-icon>
        </el-tooltip>
      </div>

    </div>
    <div class="register-link">
      没有账号？<el-link type="primary" @click="switchToRegister">立即注册</el-link>
    </div>
  </div>
</el-dialog>
<!-- 注册对话框 -->
<el-dialog
  v-model="registerDialogVisible"
  title="注册新账号"
  width="380px"
  :before-close="handleRegisterDialogClose"
  class="custom-register-dialog"
>
  <div class="register-content">
    <el-form
      :model="registerForm"
      :rules="registerRules"
      ref="registerFormRef"
      label-position="top"
    >
      <el-form-item prop="username">
        <el-input
          v-model="registerForm.username"
          placeholder="请输入用户名"
        />
      </el-form-item>

      <el-form-item prop="password">
        <el-input
          v-model="registerForm.password"
          placeholder="请输入密码"
          type="password"
          show-password
        />
      </el-form-item>

      <el-form-item prop="email">
        <el-input
          v-model="registerForm.email"
          placeholder="请输入邮箱"
          type="email"
        />
      </el-form-item>

      <el-form-item prop="phone">
        <el-input
          v-model="registerForm.phone"
          placeholder="请输入手机号"
        />
      </el-form-item>

      <el-form-item prop="genderCode">
        <el-radio-group v-model="registerForm.genderCode">
          <el-radio :label="1">男</el-radio>
          <el-radio :label="2">女</el-radio>
          <el-radio :label="3">保密</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>

    <div class="register-agreement">
      <el-checkbox v-model="registerAgreeAgreement">
        我已阅读并同意《用户协议》和《隐私政策》
      </el-checkbox>
    </div>

    <el-button
      type="primary"
      @click="handleRegister"
      :loading="registerLoading"
      :disabled="!registerAgreeAgreement"
      class="register-btn"
    >
      立即注册
    </el-button>

    <div class="login-link">
      已有账号？<el-link type="primary" @click="switchToLogin">立即登录</el-link>
    </div>
  </div>
</el-dialog>

    <!-- 主要内容区 -->
    <el-main class="main-content">
      <div class="container">
        <router-view />
        <!-- 侧边栏 -->
        <el-aside width="300px" class="sidebar"  v-if="!['NewProfile', 'addContent'].includes($route.name)">
          <TagCloud />
          <ContentHot />
          <AdBanner />
        </el-aside>
      </div>
    </el-main>

    <!-- 底部信息栏 -->
    <el-footer class="footer">
      <div class="container">
        <div class="footer-content">
          <div class="footer-section">
            <h4 class="footer-title">关于我们</h4>
            <ul class="footer-list">
              <li><router-link to="/about">公司简介</router-link></li>
              <li><router-link to="/contact">联系我们</router-link></li>
              <li><router-link to="/jobs">加入我们</router-link></li>
            </ul>
          </div>

          <div class="footer-section">
            <h4 class="footer-title">帮助中心</h4>
            <ul class="footer-list">
              <li><router-link to="/faq">常见问题</router-link></li>
              <li><router-link to="/feedback">意见反馈</router-link></li>
              <li><router-link to="/policy">隐私政策</router-link></li>
            </ul>
          </div>

          <div class="footer-section">
            <h4 class="footer-title">关注我们</h4>
            <ul class="footer-list">
              <li><router-link to="/wechat">微信公众号</router-link></li>
              <li><router-link to="/weibo">微博</router-link></li>
              <li><router-link to="/twitter">Twitter</router-link></li>
            </ul>
            <div class="social-icons">
              <el-link :underline="false" class="social-icon">
                <i class="el-icon-chat-dot-round"></i>
              </el-link>
              <el-link :underline="false" class="social-icon">
                <i class="el-icon-chat-line-round"></i>
              </el-link>
              <el-link :underline="false" class="social-icon">
                <i class="el-icon-chat-line-square"></i>
              </el-link>
            </div>
          </div>
        </div>

        <div class="footer-bottom">
          <p class="copyright">© 2025 内容平台 版权所有</p>
        </div>
      </div>
    </el-footer>

    <!-- 返回顶部按钮 -->
    <el-backtop :right="30" :bottom="30" />
  </div>
</template>

<script setup>
import { ref, computed , onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useAuthStore } from '@/stores/auth'
import TagCloud from '@/components/TagCloud.vue'
import AdBanner from '@/components/AdBanner.vue'
import ContentHot from '@/components/ContentsHot.vue'
import axios from 'axios'
import {
  Picture,
  ChatDotRound,
  ChatLineRound,
  ChatLineSquare
} from '@element-plus/icons-vue'
const route = useRoute()
const authStore = useAuthStore()
const searchQuery = ref('')
const defaultAvatar = '../images/header.png'


// 初始化检查登录状态
onMounted(async () => {
  await authStore.checkAuth()
})
// 登录对话框相关
const loginDialogVisible = ref(false)
const loginLoading = ref(false)
const phoneLoginFormRef = ref(null)
const activeLoginMethod = ref('phone')
const agreeAgreement = ref(false)
const phoneLoginForm = ref({
  phone: '',
  password: ''
})


// 注册对话框相关
const registerDialogVisible = ref(false)
const registerLoading = ref(false)
const registerFormRef = ref(null)
const registerAgreeAgreement = ref(false)
const registerForm = ref({
  username: '',
  password: '',
  email: '',
  phone: '',
  genderCode: null
})


const registerRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 16, message: '用户名长度在3到16个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在6到20个字符', trigger: 'blur' },
    // { pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[^]{6,20}$/, message: '密码必须包含大小写字母和数字', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  genderCode: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ]
}

const handleRegisterDialogClose = (done) => {
  if (registerLoading.value) {
    ElMessage.warning('注册操作正在进行中，请稍后再关闭')
    return false
  }
  registerDialogVisible.value = false
}

const handleRegister = async () => {
  try {
    await registerFormRef.value.validate()
    if (!registerAgreeAgreement.value) {
      ElMessage.warning('请同意用户协议和隐私政策')
      return
    }
    registerLoading.value = true
    // 发送注册请求
    // 假设这里有一个注册接口，返回一个Promise
    // 例如：

   const response = await axios.post('http://127.0.0.1:8081/app/users/register', registerForm.value)
    if (response.data.code !== 200) {
      throw new Error(response.data.message || '注册失败')
    }
    // 注册成功后进行登录操作
    await authStore.login(registerForm.value.phone, registerForm.value.password)
    // 注册成功后跳转到登录页面
    ElMessage.success('注册成功')
    registerDialogVisible.value = false
    loginDialogVisible.value = false // 注册成功后自动跳转到登录
  } catch (error) {
    ElMessage.error(error.message || '注册失败')
  } finally {
    registerLoading.value = false
  }
}

const switchToLogin = () => {
  registerDialogVisible.value = false
  loginDialogVisible.value = true
}

const switchToRegister = () => {
  loginDialogVisible.value = false
  registerDialogVisible.value = true
}

const phoneLoginRules = {
  phone: [
    { required: true, message: '手机号不能为空', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ]
}

const activeMenu = computed(() => route.path)

const handleSearch = () => {
  console.log('搜索:', searchQuery.value)
}

const handleDialogClose = (done) => {
  loginDialogVisible.value = false
  if (loginLoading.value) {
    ElMessage.warning('登录操作正在进行中，请稍后再关闭')
    return false
  }
}

// const sendCode = () => {
//   phoneLoginFormRef.value.validateField('phone', valid => {
//     if (valid) {
//       isCountingDown.value = true
//       countdown.value = 60
//       countdownTimer = setInterval(() => {
//         countdown.value--
//         if (countdown.value <= 0) {
//           clearInterval(countdownTimer)
//           isCountingDown.value = false
//         }
//       }, 1000)
//       // 这里添加发送验证码的逻辑
//       ElMessage.success('验证码已发送')
//     }
//   })
// }

const handlePhoneLogin = async () => {
  try {
    await phoneLoginFormRef.value.validate()
    if (!agreeAgreement.value) {
      ElMessage.warning('请同意用户协议和隐私政策')
      return
    }

    loginLoading.value = true
    await authStore.login(phoneLoginForm.value.phone, phoneLoginForm.value.password)
    ElMessage.success('登录成功')
    loginDialogVisible.value = false
  } catch (error) {
    ElMessage.error(error.message || '登录失败')
  } finally {
    loginLoading.value = false
  }
}

const handleLogout = async () => {
  try {
    await authStore.logout()
    ElMessage.success('已退出登录')
  } catch (error) {
    ElMessage.error(error.message || '退出登录失败')
  }
}
const errorHandler = () =>{
  return true
}
</script>

<style scoped>
.app-container {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

.navbar {
  background-color: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  position: sticky;
  top: 0;
  z-index: 100;
  padding: 0 20px;
}

.container {
  width: 100%;
  max-width: 1200px;
  margin: 0 auto;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.logo {
  font-size: 20px;
  font-weight: bold;
  color: var(--el-color-primary);
  text-decoration: none;
}

.main-nav {
  flex: 1;
  margin: 0 20px;
}

.user-actions {
  display: flex;
  align-items: center;
  gap: 15px;
}

.search-input {
  width: 250px;
}

.auth-buttons {
  display: flex;
  gap: 10px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.user-name {
  margin-right: 8px;
  font-size: 14px;
}

.main-content {
  flex: 1;
  padding: 20px 0;

  /* 视频背景 */

}

.main-content .container {
  display: flex;
  gap: 20px;
  align-items: flex-start;
}

.sidebar {
  position: sticky;
}

/* 登录对话框底部样式 */
.dialog-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

/* 底部样式 */
.footer {
  background-color: #333;
  color: #999;
  padding: 40px 0 20px;
  margin-top: auto;
  height: auto;
}

.footer-content {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  gap: 30px;
  margin-bottom: 30px;
}

.footer-section {
  flex: 1;
  min-width: 180px;
  max-width: 250px;
}

.footer-title {
  color: #fff;
  font-size: 16px;
  margin-bottom: 20px;
  font-weight: 500;
}

.footer-list {
  list-style: none;
  padding: 0;
  margin: 0;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.footer-list a {
  color: #999;
  text-decoration: none;
  transition: color 0.3s;
  font-size: 14px;
}

.footer-list a:hover {
  color: #fff;
}

.social-icons {
  display: flex;
  gap: 15px;
}

.social-icon {
  color: #999;
  font-size: 20px;
  transition: color 0.3s;
}

.social-icon:hover {
  color: #fff;
}

.footer-bottom {
  border-top: 1px solid #444;
  padding-top: 20px;
  text-align: center;
}

.copyright {
  color: #999;
  font-size: 14px;
  margin: 0;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .container {
    flex-direction: column;
    gap: 15px;
  }

  .main-content .container {
    flex-direction: column;
  }

  .sidebar {
    width: 100%;
  }

  .footer-content {
    flex-direction: column;
    align-items: center;
    text-align: center;
    gap: 30px;
  }

  .footer-section {
    max-width: 100%;
  }

  .social-icons {
    justify-content: center;
  }
}


.custom-login-dialog {
  .el-dialog__header {
    text-align: center;
    border-bottom: none;
    padding-bottom: 0;

    .el-dialog__title {
      font-size: 18px;
      font-weight: normal;
      color: #333;
    }
  }

  .login-content {
    padding: 0 20px;

    .el-tabs {
      .el-tabs__nav-wrap::after {
        height: 1px;
        background-color: #eee;
      }

      .el-tabs__item {
        font-size: 16px;
        padding: 0 20px;
      }
    }

    .phone-input {
      display: contents;
      gap: 10px;
      .phone-number-input {
        flex: 1;
      }
    }

    .code-input {
      display: contents;
      gap: 10px;
      .el-input {
        flex: 1;
      }

      .send-code-btn {
        width: 120px;
      }
    }

    .qrcode-login {
      display: flex;
      flex-direction: column;
      align-items: center;
      padding: 30px 0;

      .qrcode-placeholder {
        text-align: center;
        color: #999;

        p {
          margin: 10px 0 0;
          font-size: 14px;
        }
      }
    }

    .login-agreement {
      margin: 15px 0;
      text-align: center;

      .el-checkbox {
        font-size: 12px;
        color: #999;
      }
    }

    .login-btn {
      width: 100%;
      margin-bottom: 20px;
    }

    .other-login-methods {
      .divider {
        display: flex;
        align-items: center;
        margin: 20px 0;
        color: #999;
        font-size: 12px;

        &::before, &::after {
          content: "";
          flex: 1;
          height: 1px;
          background: #eee;
        }

        .divider-text {
          padding: 0 10px;
        }
      }

      .social-logins {
        display: flex;
        justify-content: center;
        gap: 20px;
        margin-bottom: 10px;

        .el-icon {
          cursor: pointer;
          color: #666;

          &:hover {
            color: var(--el-color-primary);
          }
        }
      }
    }
  }
}

/* 在App.vue的style部分添加 */
.custom-login-dialog .el-dialog__body {
  padding: 20px;
}

.login-content {
  max-width: 100%;
}

.phone-input, .code-input {
  margin-bottom: 20px;
}

.login-btn {
  margin-top: 10px;
}

.login-agreement {
  margin: 15px 0;
  text-align: center;
  font-size: 12px;
  color: #999;
}

/* 注册对话框样式 */
.custom-register-dialog {
  .el-dialog__header {
    text-align: center;
    border-bottom: none;
    padding-bottom: 0;

    .el-dialog__title {
      font-size: 18px;
      font-weight: normal;
      color: #333;
    }
  }

  .register-content {
    padding: 0 20px;

    .el-form-item {
      margin-bottom: 20px;
    }

    .register-agreement {
      margin: 15px 0;
      text-align: center;

      .el-checkbox {
        font-size: 12px;
        color: #999;
      }
    }

    .register-btn {
      width: 100%;
      margin-bottom: 15px;
    }

    .login-link {
      text-align: center;
      font-size: 14px;
      color: #666;

      .el-link {
        margin-left: 5px;
      }
    }
  }

}

.register-link {
      text-align: center;
      font-size: 14px;
      color: #666;

      .el-link {
        margin-left: 5px;
      }
    }
</style>
